package sshj;

import com.trilead.ssh2.SCPClient;
import io.SshBean;
import jschtest.ThreadPoolUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.schmizz.sshj.xfer.FileSystemFile;
import net.schmizz.sshj.xfer.scp.SCPUploadClient;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author Mu
 * @Date 2020/11/19 15:01
 */
public class SSHJTool {

    private static ThreadPoolExecutor executor = ThreadPoolUtil.getInstance(Integer.valueOf(0));

    //上传文件
    public static boolean installSoftware(SshBean sshBean,String src,String dest,boolean isMonitor){
        SSHClient sshClient = null;
        SFTPClient sftpClient = null;
        try {
            sshClient = new SSHClient();

            setSSHClient(sshClient,sshBean);

            sftpClient = sshClient.newSFTPClient();

            //监控文件进度
            if (isMonitor) {
                Timer timer = new Timer();
                long fileSize = new File(src).length();
                String fileName = src.substring(src.lastIndexOf(File.separator) + 1);
                String destPath = "";
                if (dest.lastIndexOf("/") == (dest.length() - 1)){
                    destPath = dest + fileName;
                } else {
                    destPath = dest + "/" + fileName;
                }
                TransferMonitor transferMonitor = new TransferMonitor(fileSize,sshBean,destPath);
                timer.schedule(transferMonitor,1000,5 * 1000);
            }


            System.out.println("传输文件开始");
            if (!SSHJUtil.uploadFile(src,dest,sftpClient)){
                return false;
            }
            System.out.println("传输文件结束");
            return true;
        } catch (IOException e){
            System.out.println("upload file fail");
            return false;

        } finally {
            if (sftpClient != null){
                try {
                    sftpClient.close();
                } catch (IOException e){
                    System.out.println("upload file success, close sftpClient fail");
                    return false;
                }
            }
            if (sshClient != null){
                try {
                    sshClient.disconnect();
                } catch (IOException e){
                    System.out.println("upload file success, close ssh fail");
                    return false;
                }
            }
        }
    }

    public static boolean installSoftwareBySCP(SshBean sshBean,String src,String dest,String rootPass,boolean needExtract){
        SSHClient sshClient = null;
        SCPUploadClient scpClient = null;
        try {
            sshClient = new SSHClient();

            setSSHClient(sshClient,sshBean);

            scpClient = sshClient.newSCPFileTransfer().newSCPUploadClient();
            System.out.println("传输文件开始");
            if (!SSHJUtil.uploadFileBySCP(src,dest,scpClient)){
                return false;
            }
            System.out.println("传输文件结束");
            System.out.println("解压文件开始");
            if (needExtract){
                if (src.contains(".zip")){
                    String command = "unzip -d " + dest + " /home/jsch/test.zip";
                    SSHJUtil.execCommand(command,sshClient,rootPass);
                } else if (src.contains("tar.gz")){

                } else {
                    System.out.println("暂不支持该类型文件解压");
                }

            }

            System.out.println("解压文件结束");
            System.out.println("软件安装开始");
            System.out.println("软件安装结束");
            return true;
        } catch (IOException e){
            System.out.println("upload file fail");
            return false;

        } finally {
            if (sshClient != null){
                try {
                    sshClient.disconnect();
                } catch (IOException e){
                    System.out.println("upload file success, close ssh fail");
                    return false;
                }
            }
        }
    }

    //下载文件
    //上传并执行脚本
    public static boolean executeShellScript(SshBean sshBean,String src,String rootPass){
        SSHClient sshClient = null;
        SFTPClient sftpClient = null;
        try {
            sshClient = new SSHClient();

            setSSHClient(sshClient,sshBean);

            sftpClient = sshClient.newSFTPClient();
            long start = System.currentTimeMillis();
            String dest = "/home/ispim/";
            if (!SSHJUtil.uploadFile(src,dest,sftpClient)){
                return false;
            }
            String fileName = src.substring(src.lastIndexOf(File.separator) + 1);
            String filePath = null;
//            System.out.println("/ index is :" + dest.lastIndexOf("/"));
//            System.out.println("/ dest length is  is :" + (dest.length() -1));
            if (dest.lastIndexOf("/") == (dest.length() - 1)){
                filePath = dest + fileName;
            } else {
                filePath = dest + "/" + fileName;
            }
            System.out.println("file path is :" + filePath);
            if (!SSHJUtil.chmodFile(filePath,777,sftpClient)){
                return false;
            }
            String result = SSHJUtil.execCommand(filePath,sshClient,rootPass);
//            sftpClient.close();
//            String command = "";
            System.out.println("sshj execute command result is :" + result);
            if (!SSHJUtil.deleteFile(filePath,sftpClient)){
                return false;
            }
            return true;
        } catch (IOException e){
            System.out.println(e);
            System.out.println("upload file fail" + e);
            return false;

        } finally {
            if (sftpClient != null){
                try {
                    sftpClient.close();
                } catch (IOException e){
                    System.out.println("upload file success, close sftpClient fail");
                    return false;
                }
            }
            if (sshClient != null){
                try {
                    sshClient.disconnect();
                } catch (IOException e){
                    System.out.println("upload file success, close ssh fail");
                    return false;
                }
            }
        }
    }

    public static boolean executeCommand(SshBean sshBean,String command,String rootPass){
        SSHClient sshClient = null;
        SFTPClient sftpClient = null;
        try {
            sshClient = new SSHClient();

            setSSHClient(sshClient,sshBean);

            sftpClient = sshClient.newSFTPClient();

            String result = SSHJUtil.execCommand(command,sshClient,rootPass);
//            sftpClient.close();
//            String command = "";
            System.out.println("sshj execute command result is :" + result);
            return true;
        } catch (IOException e){
            System.out.println(e);
            System.out.println("upload file fail" + e);
            return false;

        } finally {
            if (sftpClient != null){
                try {
                    sftpClient.close();
                } catch (IOException e){
                    System.out.println("upload file success, close sftpClient fail");
                    return false;
                }
            }
            if (sshClient != null){
                try {
                    sshClient.disconnect();
                } catch (IOException e){
                    System.out.println("upload file success, close ssh fail");
                    return false;
                }
            }
        }
    }

    private static void setSSHClient(SSHClient sshClient,SshBean sshBean) throws IOException{
        sshClient.addHostKeyVerifier(new PromiscuousVerifier());
        sshClient.connect(sshBean.getIp());
        sshClient.authPassword(sshBean.getUsername(), sshBean.getPassword());

    }
}
